<template>
  <div class="catelist">
    <el-dialog
      :title="state ? '编辑分类' : '添加分类'"
      :visible.sync="dialogFormVisible"
      :before-close="cancel"
    >
      <el-form
        :model="submitData"
        status-icon
        :label-position="labelPosition"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div class="flex-col-24 upload-wrapper">
          <span class="label">分类图片</span>
          <div class="upload-box">
            <el-upload
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :multiple="false"
              :on-change="uploadFile"
              drag
              accept="image/jpg,image/jpeg,image/png"
            >
              <i
                v-if="imageUrl"
                class="el-icon-circle-close deleteImg"
                @click.stop="handleRemove"
              ></i>
              <img
                v-if="imageUrl"
                :src="imageUrl"
                class="el-upload--picture-car"
              />
              <div
                style="
                  display: flex;
                  align-item: center;
                  flex-direction: column;
                  justify-content: center;
                  background-color: var(--bg-primary-color);
                  height: 100%;
                "
                v-else
              >
                <i
                  class="el-icon-picture"
                  style="font-size: 40px; color: #d9d9d9"
                ></i>
              </div>
            </el-upload>
            <el-button
              class="send"
              plain
              type="primary"
              size="small"
              @click="submitOrder"
              >上传图片</el-button
            >
          </div>
        </div>
        <div class="flex-col-12">
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="submitData.name"></el-input>
          </el-form-item>
        </div>
        <div class="flex-col-12">
          <el-form-item label="排序号" prop="orders">
            <el-input v-model.number="submitData.orders"></el-input>
          </el-form-item>
        </div>
        <div class="flex-col-12" v-if="!isChild">
          <el-form-item label="分类级别">
            <el-select @change="selectChanged" v-model="submitData.level" placeholder="请选择分类级别">
              <el-option label="一级分类" :value="0"></el-option>
              <el-option label="二级分类" :value="1"></el-option>
              <el-option label="三级分类" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="flex-col-12" v-if="submitData.level !== 0 && !isChild">
          <el-form-item label="父级分类">
            <el-select
              v-model="submitData.parentId"
              placeholder="请选择父级分类"
            >
              <el-option
                label="一级分类"
                v-for="category in cateOptions"
                :value="category.id"
                :key="category.id"
                :label="category.name"
                ></el-option
              >
            </el-select>
          </el-form-item>
        </div>
        <div class="flex-col-12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="submitData.status" placeholder="状态">
              <el-option label="启用" :value="1"></el-option>
              <el-option label="禁用" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <div class="inner-container container">
      <div class="filter-container flex-row">
        <div class="flex-col-3 input-box">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入分类名称"
          ></el-input>
        </div>
        <div class="flex-col-3 input-box">
          <el-select v-model="queryParams.status" placeholder="请选择状态">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <div class="btn-box">
          <el-button
            type="primary"
            icon="el-icon-search"
            plain
            @click="search"
            v-permission="{ action: 'view', effect: 'disabled' }"
            >搜索</el-button
          >
          <el-button
            type="success"
            icon="el-icon-edit"
            plain
            @click="addData"
            v-permission="{ action: 'add', effect: 'disabled' }"
            >添加</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            plain
            v-permission="{ action: 'delete', effect: 'disabled' }"
            @click="batchDelete"
            >批量删除</el-button
          >
        </div>
      </div>
      <el-table
        :data="tableData"
        border
        row-key="id"
        v-loading="loading"
        ref="multipleTable"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :header-cell-style="{
          background: 'var(--primary-color)',
          color: 'var(--text-sidebar-hover-color)',
        }"
      >
        <el-table-column align="center" type="selection" width="55">
        </el-table-column>
        <el-table-column align="center" type="index" label="ID" width="66">
        </el-table-column>
        <el-table-column align="center" prop="name" label="分类名称" width="180">
        </el-table-column>
        <el-table-column align="center" label="图片" width="56">
          <template slot-scope="scope">
            <img
              v-if="scope.row.picture"
              style="width: 100%; border-radius: 10px"
              :src="
                scope.row.picture ? `${$upload_path}/${scope.row.picture}` : ''
              "
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="分类级别">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.level === 0" type="primary">一级分类</el-tag>
            <el-tag v-if="scope.row.level === 1" type="warning">二级分类</el-tag>
            <el-tag v-if="scope.row.level === 2" type="info">三级分类</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="orders" label="排序号">
        </el-table-column>
        <el-table-column align="center" prop="createTime" label="创建时间" width="180">
        </el-table-column>
        <el-table-column align="center" prop="createUser" label="创建者">
        </el-table-column>
        <el-table-column align="center" prop="updateTime" label="修改时间" width="180">
        </el-table-column>
        <el-table-column align="center" prop="updateUser" label="操作者">
        </el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">{{
              scope.row.status === 1 ? '启用' : '禁用'
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="260">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.level !== 2"
              plain
              type="success"
              class="add"
              icon="el-icon-plus"
              v-permission="{ action: 'add', effect: 'disabled' }"
              @click="addChild(scope.row)"
              >添加</el-button
            >
            <el-button
              plain
              type="primary"
              class="edit"
              icon="el-icon-edit"
              v-permission="{ action: 'update', effect: 'disabled' }"
              @click="editData(scope.row)"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定删除吗？"
              @confirm="handleDeleteRow(scope.row.id)"
            >
              <el-button
                v-permission="{ action: 'delete', effect: 'disabled' }"
                plain
                type="danger"
                icon="el-icon-delete"
                slot="reference"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
        <template slot="empty">
          <el-empty :image-size="200" description="暂无数据"></el-empty>
        </template>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  pageQuery,
  insert,
  update,
  deleteData,
  categoryEffectiveOptions,
} from '@/api/category'
import { getTableData, handleVoidMethod } from '@/api/table'
import { upload } from '@/api/upload'
export default {
  name: 'MyBrandList',
  data() {
    return {
      options: [
        {
          value: -1,
          label: '全部',
        },
        {
          value: 0,
          label: '禁用',
        },
        {
          value: 1,
          label: '启用',
        },
      ],
      tableData: [],
      cateOptions: [],
      multipleSelection: [],
      queryParams: {
        name: '',
        status: -1,
        page: 1,
        pageSize: 10,
      },
      submitData: {
        name: '',
        orders: '',
        picture: '',
        level: '',
        parentId: '',
        status: '',
      },
      rules: {
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
      },
      total: 0,
      state: false,
      loading: false,
      imageUrl: '',
      currentPage: 1,
      labelPosition: 'right',
      isChild: false,
      dialogFormVisible: false,
    }
  },
  created() {
    this.getTableData()
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.queryParams.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.queryParams.page = val
      this.getTableData()
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.state
            ? handleVoidMethod(
                this,
                '修改成功',
                '修改失败',
                update(this.submitData),
                this.cancel
              )
            : handleVoidMethod(
                this,
                '添加成功',
                '添加失败',
                insert(this.submitData),
                this.cancel
              )
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleSelectionChange(val) {
      this.multipleSelection = []
      val.forEach((item) => {
        const { id } = item
        this.multipleSelection.push(id)
      })
    },
    uploadFile(item) {
      this.formData = item.raw // 图片文件
      this.imageUrl = URL.createObjectURL(item.raw) // 图片上传浏览器回显地址
      console.log(this.imageUrl, 'imageUrl')
      console.log(this.formData, 'formData')
    },
    handleRemove() {
      this.imageUrl = ''
      this.formData = null
      console.log(this.formData)
      console.log('QAQ')
    },
    async submitOrder() {
      var formData = new FormData()
      formData.append('file', this.formData) // 照片文件
      const { data: res, code } = await upload(formData)
      if (code === 200) {
        this.$message({ type: 'success', message: '上传成功' })
      } else {
        this.$message({ type: 'error', message: '上传失败' })
      }
      this.submitData.picture = res
    },
    handleDeleteRow(id) {
      console.log(id)
      handleVoidMethod(this, '删除成功', '删除失败', deleteData([id]))
    },
    cancel() {
      this.submitData = {}
      this.dialogFormVisible = false
    },
    getTableData() {
      this.loading = true
      getTableData(this, pageQuery(this.queryParams))
    },
    async selectChanged(val) {
      console.log(val);
      const { data: res } = await categoryEffectiveOptions(val)
      this.cateOptions = res
      if(val === 0) {
        this.submitData.parentId = ''
      }
    },
    search() {
      this.getTableData()
    },
    addData() {
      this.state = false
      this.isChild = false
      this.imageUrl = ''
      this.submitData = {}
      this.dialogFormVisible = true
    },
    addChild(item) {
      this.state = false
      this.isChild = true
      this.imageUrl = ''
      this.submitData.level = item.level + 1
      this.submitData.parentId = item.id
      this.dialogFormVisible = true
    },
    editData(item) {
      this.state = true
      this.isChild = false
      const category = JSON.parse(JSON.stringify(item))
      this.imageUrl = category.picture ? `${this.$upload_path}/${category.picture}` : ''
      categoryEffectiveOptions(item.level).then(res => {
        this.cateOptions = res.data
      })
      this.submitData = JSON.parse(JSON.stringify(item))
      this.dialogFormVisible = true
    },
    batchDelete() {
      if (this.multipleSelection.length <= 0) {
        return this.$message({ type: 'warning', message: '请选择对象' })
      }
      handleVoidMethod(
        this,
        '删除成功',
        '删除失败',
        deleteData(this.multipleSelection)
      )
    },
  },
}
</script>

<style lang="less" scoped>
.catelist {
  padding: 10px;
  box-sizing: border-box;
  .filter-container {
    flex-wrap: wrap;
    box-sizing: border-box;
    margin-bottom: 20px;
  }
  .inner-container {
    box-sizing: border-box;
    border-radius: 5px;
    padding: 20px;
    background-color: var(--bg-primary-color);
    transition: var(--tran-01);
  }
  .input-box {
    margin-right: 10px;
  }
}
.el-select {
  width: 100%;
}
/deep/ .el-dialog {
  background: var(--bg-primary-color);
  transition: var(--tran-01);
}
/deep/ .el-dialog__title {
  color: var(--text-normal-color) !important;
  transition: var(--tran-01);
}
/deep/ .el-form-item__label {
  color: var(--text-normal-color) !important;
  transition: var(--tran-01);
}
.el-form {
  display: flex;
  flex-wrap: wrap;
}
/deep/ .el-form-item__label {
  text-align: center !important;
}
.el-pagination {
  margin-top: 20px;
}

/deep/ .el-pagination button {
  background-color: var(--bg-primary-color);
  transition: var(--tran-01);
}
/deep/ .el-pager li {
  background-color: var(--bg-primary-color);
  transition: var(--tran-01);
}
/deep/ .el-pager li.active {
  color: var(--primary-color);
  background-color: var(--bg-primary-color);
  transition: var(--tran-01);
}
/deep/ .el-pagination__total {
  color: var(--text-normal-color);
  transition: var(--tran-01);
}
/deep/ .el-pagination__jump {
  color: var(--text-normal-color);
  transition: var(--tran-01);
}
.btn-box {
  display: flex;
  flex-wrap: wrap;
}
/deep/ .el-button {
  flex-grow: 1;
}
/deep/ .el-input .el-input__inner {
  color: var(--text-normal-color);
  background-color: var(--history-color) !important;
  transition: var(--tran-01);
}

/deep/ .el-select-dropdown {
  background-color: var(--history-color) !important;
}
/deep/ .el-table,
.el-table__expanded-cell {
  background-color: transparent;
}

/deep/ .el-table__body-wrapper.is-scrolling-left::-webkit-scrollbar,
/deep/ .el-table__body-wrapper.is-scrolling-right::-webkit-scrollbar,
/deep/ .el-table__body-wrapper.is-scrolling-middle::-webkit-scrollbar {
  height: 5px;
}
/deep/ .el-table__body-wrapper.is-scrolling-left::-webkit-scrollbar-thumb,
/deep/ .el-table__body-wrapper.is-scrolling-right::-webkit-scrollbar-thumb,
/deep/ .el-table__body-wrapper.is-scrolling-middle::-webkit-scrollbar-thumb {
  background: #ccc; // 滑块颜色
  border-radius: 6px; // 滑块圆角
}
/deep/ .el-table__body-wrapper.is-scrolling-left::-webkit-scrollbar-track,
/deep/ .el-table__body-wrapper.is-scrolling-right::-webkit-scrollbar-track,
/deep/ .el-table__body-wrapper.is-scrolling-middle::-webkit-scrollbar-track {
  border-radius: 10px; // 轨道圆角
  background-color: #fff // 轨道颜色 ;
}
/deep/ .el-table tr {
  color: var(--text-normal-color);
  background-color: var(--history-color);
  transition: var(--tran-01);
}

/deep/ .el-textarea__inner {
  color: var(--text-normal-color);
  background-color: var(--history-color);
  transition: var(--tran-01);
}

/deep/ .el-table .cell {
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden; //多出的隐藏
  //text-overflow: ellipsis;//多出部分用...代替
  display: -webkit-box; //定义为盒子模型显示
  -webkit-line-clamp: 2; //用来限制在一个块元素显示的文本的行数
  -webkit-box-orient: vertical; //从上到下垂直排列子元素（设置伸缩盒子的子元素排列方式）
}

/deep/ .el-table__body tr:hover > td {
  background-color: #a69ff5 !important;
  color: var(--text-sidebar-hover-color);
}

/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

/deep/ .el-upload-dragger {
  width: 100px;
  height: 100px;
}

.deleteImg {
  font-size: 20px;
  position: absolute;
  top: 0;
  right: 0;
  z-index: 999;
}

img {
  width: 100%;
  height: 100%;
  background-repeat: no-repeat;
}
.upload-wrapper {
  display: flex;
  margin-bottom: 20px;
  .label {
    box-sizing: border-box;
    width: 100px;
    padding: 0 12px 0 0;
    text-align: center;
    color: var(--text-normal-color);
    transition: var(--tran-01);
  }
  .send {
    width: 100px;
    margin-top: 10px;
  }
}

.edit {
  margin-right: 10px;
}
</style>
